package org.example.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.poi.ss.usermodel.*;
import org.example.R.R;
import org.example.constants.CoreConstants;
import org.example.entity.dto.EditPartyOrganizationInfoDto;
import org.example.entity.po.DynamicExcelData;
import org.example.entity.vo.PartyBuildingGuidanceTableVO;
import org.example.entity.vo.PartyOrganizationInfoVO;
import org.example.mapper.PartyBuildingGuidanceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PartyBuildingGuidanceService {


    @Autowired
    private PartyBuildingGuidanceMapper partyBuildingGuidanceMapper;

    @Transactional(rollbackFor = Exception.class)
    public R importExcelToTable(MultipartFile excelFile, String tableName) {

        StringBuilder sqlStr = new StringBuilder("");
        sqlStr.append("insert into ");
        sqlStr.append(tableName);
        sqlStr.append(" (");
        try {
            Workbook workbook = WorkbookFactory.create(excelFile.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            // 获取第一行作为表头
            Row headerRow = sheet.getRow(0);
            //表字段名列表
            List<Object> columnNames = new ArrayList<>();
            columnNames.add("id");
            for (Cell cell : headerRow) {
                if (StrUtil.isNotBlank(cell.getStringCellValue())) {
                    columnNames.add(cell.getStringCellValue());
                }
            }
            String columnName = String.join(",", String.valueOf(columnNames));
            sqlStr.append(columnName.replaceAll("[\\[\\]]", ""));
            sqlStr.append(" )");
            // 创建数据库表
            partyBuildingGuidanceMapper.dropTableIfExists(tableName);
            partyBuildingGuidanceMapper.createTable(tableName, columnNames);

            // 从第二行开始插入数据
            sqlStr.append(" values");

            for (int i = 1; i < sheet.getLastRowNum(); i++) {
                List<String> element = new ArrayList<>();
                Row row = sheet.getRow(i);
                if (row == null) {
                    break;
                }
                sqlStr.append(" (");
                int cellNum = row.getLastCellNum();
                element.add(String.valueOf(IdUtil.getSnowflakeNextId()));
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        cell.setCellType(CellType.STRING);
                        if (StrUtil.isNotBlank(cell.getStringCellValue())) {
                            element.add("'" + cell.getStringCellValue() + "'");
                        }else {
                            element.add("'" + "暂无" + "'");
                        }
                    }else {
                        element.add("'" + "暂无" + "'");
                    }
                }
                String columnValue = String.join(",", String.valueOf(element));
                sqlStr.append(columnValue.replaceAll("[\\[\\]]", ""));
                sqlStr.append(" )");
                sqlStr.append(",");
            }
            sqlStr.deleteCharAt(sqlStr.length() - 1);
            partyBuildingGuidanceMapper.insertTable(sqlStr.toString());
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success("导入成功!");
    }

    private List<String> showTableColumn(String tableName) {
        List<String> headerColumns = partyBuildingGuidanceMapper.selectHeaderColumns(tableName);
        Collections.rotate(headerColumns, 1);
        return headerColumns;
    }

    private List<Map<String, Object>> showTableData(String tableName) {
        List<Map<String, Object>> tableData = partyBuildingGuidanceMapper.selectTableData(tableName);
        Set<Map<String, Object>> sortedData = new HashSet<>();

        // 遍历原始列表，找到包含id的第一个Map并添加到新列表的开头
        for (Map<String, Object> row : tableData) {
            if (row.containsKey("id")) {
                sortedData.add(row);
                break;
            }
        }
        // 将原始列表中剩余的Map添加到新列表的末尾
        sortedData.addAll(tableData);
        return sortedData.stream().collect(Collectors.toList());
    }

    public R getTableInfo(String tableName) {
        PartyBuildingGuidanceTableVO response = new PartyBuildingGuidanceTableVO();
        boolean tableExist = partyBuildingGuidanceMapper.selectTableExist(tableName);
        if (!tableExist) {
            return R.success("初始化").setData(response);
        }
        response.setTableColumns(showTableColumn(tableName));
        response.setTableData(showTableData(tableName));
        return R.success("获取成功!").setData(response);
    }

    public R deleteElement(String tableName, Long id) {
        if (partyBuildingGuidanceMapper.selectTableExist(tableName)) {
            partyBuildingGuidanceMapper.deleteElement(tableName, id);
            return R.success("删除成功!");
        }
        return R.error("数据库表" + tableName + "不存在!");
    }

    public R groupInfo() {
        PartyOrganizationInfoVO groupInfo = partyBuildingGuidanceMapper.groupInfo();

        return R.success("获取成功!").setData(groupInfo);
    }

    public R edit(EditPartyOrganizationInfoDto dto) {
        partyBuildingGuidanceMapper.edit(dto);
        return R.success("修改成功!");
    }
}
